<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text>←</text>
      </view>
      <text class="header-title">{{ headerTitle }}</text>
      <view class="header-actions">
        <text class="filter-btn" @click="showFilter = true">筛选</text>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-box">
      <input
        class="search-input"
        placeholder="搜索菜品..."
        v-model="searchKeyword"
        @confirm="handleSearch"
      />
      <text class="search-icon">🔍</text>
    </view>

    <!-- 分类导航 -->
    <scroll-view class="category-scroll" scroll-x="true">
      <view 
        v-for="category in categories" 
        :key="category.value"
        :class="['category-item', { active: activeCategory === category.value }]"
        @click="selectCategory(category.value)"
      >
        <text>{{ category.label }}</text>
      </view>
    </scroll-view>

    <!-- 菜单列表 -->
    <view class="menu-list">
      <view 
        v-for="item in filteredItems" 
        :key="item.id"
        class="menu-item"
        @click="viewItemDetail(item)"
      >
        <image :src="item.image || '/static/food/default.jpg'" class="item-image" />
        <view class="item-info">
          <view class="item-header">
            <text class="item-name">{{ currentLanguage === 'zh-CN' ? item.name : item.name_en }}</text>
            <text class="item-price">${{ item.price }}</text>
          </view>
          <text class="item-desc">{{ currentLanguage === 'zh-CN' ? item.description : item.description_en }}</text>
          <view class="item-tags">
            <text v-if="item.spicy_level > 0" class="tag spicy">🌶️ {{ getSpicyText(item.spicy_level) }}</text>
            <text v-if="item.tags && item.tags.includes('vegetarian')" class="tag vegetarian">🥬 素食</text>
          </view>
          <view class="item-actions">
            <text class="add-btn" @click.stop="addToCart(item)">+ 加入购物车</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredItems.length === 0" class="empty-state">
      <text class="empty-icon">🍽️</text>
      <text class="empty-text">暂无菜品</text>
    </view>

    <!-- 筛选弹窗 -->
    <uni-popup ref="filterPopup" type="bottom">
      <view class="filter-popup">
        <view class="popup-header">
          <text class="popup-title">筛选</text>
          <text class="popup-close" @click="showFilter = false">×</text>
        </view>
        <view class="filter-options">
          <view class="filter-group">
            <text class="filter-label">辣度</text>
            <view class="filter-buttons">
              <text 
                v-for="level in spicyLevels" 
                :key="level.value"
                :class="['filter-btn', { active: filters.spicy_level === level.value }]"
                @click="toggleSpicyFilter(level.value)"
              >
                {{ level.label }}
              </text>
            </view>
          </view>
          <view class="filter-group">
            <text class="filter-label">标签</text>
            <view class="filter-buttons">
              <text 
                v-for="tag in availableTags" 
                :key="tag.value"
                :class="['filter-btn', { active: filters.tags.includes(tag.value) }]"
                @click="toggleTagFilter(tag.value)"
              >
                {{ tag.label }}
              </text>
            </view>
          </view>
        </view>
        <view class="popup-actions">
          <text class="action-btn reset" @click="resetFilters">重置</text>
          <text class="action-btn apply" @click="applyFilters">应用</text>
        </view>
      </view>
    </uni-popup>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <view class="loading-spinner"></view>
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
import { mapMutations } from 'vuex'

export default {
  data() {
    return {
      menuItems: [],
      loading: false,
      searchKeyword: '',
      activeCategory: 'all',
      currentLanguage: uni.getStorageSync('language') || 'zh-CN',
      showFilter: false,
      filters: {
        spicy_level: null,
        tags: []
      },
      categories: [
        { value: 'all', label: '全部' },
        { value: 'appetizers', label: '开胃菜' },
        { value: 'main-courses', label: '主菜' },
        { value: 'noodles', label: '面条' },
        { value: 'rice', label: '米饭' },
        { value: 'drinks', label: '饮料' },
        { value: 'desserts', label: '甜点' }
      ],
      spicyLevels: [
        { value: 1, label: '微辣' },
        { value: 2, label: '中辣' },
        { value: 3, label: '重辣' }
      ],
      availableTags: [
        { value: 'vegetarian', label: '素食' },
        { value: 'spicy', label: '辣味' },
        { value: 'hot', label: '热菜' },
        { value: 'cold', label: '冷菜' }
      ]
    }
  },

  computed: {
    headerTitle() {
      if (this.$route.query.search) {
        return `搜索: ${this.$route.query.search}`
      }
      if (this.$route.query.category && this.$route.query.category !== 'all') {
        const category = this.categories.find(c => c.value === this.$route.query.category)
        return category ? category.label : '菜单'
      }
      return '全部菜单'
    },

    filteredItems() {
      let items = this.menuItems

      // 分类筛选
      if (this.activeCategory !== 'all') {
        items = items.filter(item => item.category === this.activeCategory)
      }

      // 搜索筛选
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        items = items.filter(item => 
          item.name.toLowerCase().includes(keyword) ||
          item.name_en.toLowerCase().includes(keyword) ||
          item.description.toLowerCase().includes(keyword) ||
          item.description_en.toLowerCase().includes(keyword)
        )
      }

      // 辣度筛选
      if (this.filters.spicy_level) {
        items = items.filter(item => item.spicy_level === this.filters.spicy_level)
      }

      // 标签筛选
      if (this.filters.tags.length > 0) {
        items = items.filter(item => {
          if (!item.tags) return false
          return this.filters.tags.some(tag => item.tags.includes(tag))
        })
      }

      return items
    }
  },

  onLoad(options) {
    if (options.search) {
      this.searchKeyword = options.search
    }
    if (options.category) {
      this.activeCategory = options.category
    }
    this.loadMenuItems()
  },

  methods: {
    ...mapMutations(['addToCart']),

    async loadMenuItems() {
      this.loading = true
      try {
        let url = 'http://localhost/api/menu'
        if (this.activeCategory !== 'all') {
          url += `?category=${this.activeCategory}`
        }

        const res = await uni.request({
          url: url,
          method: 'GET'
        })
        
        if (res.data.success) {
          this.menuItems = res.data.data
        }
      } catch (error) {
        console.error('加载菜单失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.loadMenuItems()
    },

    selectCategory(category) {
      this.activeCategory = category
      this.loadMenuItems()
    },

    viewItemDetail(item) {
      uni.navigateTo({
        url: `/pages/menu/detail?id=${item.id}`
      })
    },

    addToCart(item) {
      this.$store.commit('addToCart', {
        id: item.id,
        name: this.currentLanguage === 'zh-CN' ? item.name : item.name_en,
        price: item.price,
        image: item.image,
        quantity: 1
      })
      
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      })
    },

    goBack() {
      uni.navigateBack()
    },

    getSpicyText(level) {
      const levels = {
        1: '微辣',
        2: '中辣', 
        3: '重辣'
      }
      return levels[level] || ''
    },

    toggleSpicyFilter(level) {
      this.filters.spicy_level = this.filters.spicy_level === level ? null : level
    },

    toggleTagFilter(tag) {
      const index = this.filters.tags.indexOf(tag)
      if (index > -1) {
        this.filters.tags.splice(index, 1)
      } else {
        this.filters.tags.push(tag)
      }
    },

    applyFilters() {
      this.showFilter = false
      // 筛选逻辑已经在computed中处理
    },

    resetFilters() {
      this.filters = {
        spicy_level: null,
        tags: []
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 0;
  background: #f8f8f8;
  min-height: 100vh;
}

.header {
  background: white;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  font-size: 36rpx;
  padding: 10rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.filter-btn {
  color: #ff6b6b;
  font-size: 28rpx;
}

.search-box {
  padding: 20rpx 30rpx;
  background: white;
  position: relative;
}

.search-input {
  background: #f8f8f8;
  border-radius: 30rpx;
  padding: 20rpx 60rpx 20rpx 30rpx;
  font-size: 28rpx;
}

.search-icon {
  position: absolute;
  right: 50rpx;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.category-scroll {
  background: white;
  padding: 20rpx 30rpx;
  white-space: nowrap;
}

.category-item {
  display: inline-block;
  padding: 16rpx 32rpx;
  margin-right: 20rpx;
  border-radius: 30rpx;
  background: #f8f8f8;
  color: #666;
  font-size: 28rpx;
}

.category-item.active {
  background: #ff6b6b;
  color: white;
}

.menu-list {
  padding: 20rpx;
}

.menu-item {
  background: white;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
  display: flex;
}

.item-image {
  width: 200rpx;
  height: 200rpx;
  background: #e0e0e0;
}

.item-info {
  flex: 1;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15rpx;
}

.item-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  margin-right: 20rpx;
}

.item-price {
  font-size: 36rpx;
  color: #ff6b6b;
  font-weight: bold;
}

.item-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 15rpx;
  line-height: 1.4;
}

.item-tags {
  margin-bottom: 20rpx;
}

.tag {
  display: inline-block;
  padding: 8rpx 16rpx;
  border-radius: 15rpx;
  font-size: 22rpx;
  margin-right: 10rpx;
}

.tag.spicy {
  background: #ffeaa7;
  color: #d35400;
}

.tag.vegetarian {
  background: #55efc4;
  color: #00b894;
}

.item-actions {
  margin-top: auto;
}

.add-btn {
  background: #ff6b6b;
  color: white;
  padding: 16rpx 32rpx;
  border-radius: 25rpx;
  font-size: 26rpx;
  font-weight: 500;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 32rpx;
}

.filter-popup {
  background: white;
  border-radius: 30rpx 30rpx 0 0;
  padding: 40rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
}

.filter-group {
  margin-bottom: 40rpx;
}

.filter-label {
  display: block;
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.filter-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.filter-btn {
  padding: 16rpx 32rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 25rpx;
  font-size: 26rpx;
  color: #666;
}

.filter-btn.active {
  border-color: #ff6b6b;
  background: #ff6b6b;
  color: white;
}

.popup-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 40rpx;
}

.action-btn {
  flex: 1;
  text-align: center;
  padding: 25rpx;
  border-radius: 25rpx;
  font-size: 30rpx;
  font-weight: 500;
}

.action-btn.reset {
  background: #f8f8f8;
  color: #666;
}

.action-btn.apply {
  background: #ff6b6b;
  color: white;
}

.loading {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}

.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #ff6b6b;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>